package com.cy.open_wx_scan

import android.content.Context
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.PackageManager
import android.util.Log
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import java.security.AccessController.getContext


/** OpenWxScanPlugin */
class OpenWxScanPlugin: FlutterPlugin, MethodCallHandler {

  private lateinit var channel : MethodChannel
  private lateinit var context: Context

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    context = flutterPluginBinding.applicationContext
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "open_wx_scan")
    channel.setMethodCallHandler(this)
  }

  override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
    when(call.method) {
      "getPlatformVersion" -> result.success("Android ${android.os.Build.VERSION.RELEASE}")
      "openWxScan" -> {
        val intent: Intent? = context.packageManager.getLaunchIntentForPackage("com.tencent.mm")
        Log.d("plugin", "intent: ${(intent != null)}")
        if (intent != null && context.packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
          Log.d("plugin", (context.packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null).toString())
          intent.putExtra("LauncherUI.From.Scaner.Shortcut", true)
          intent.action = "android.intent.action.VIEW"
          intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
          try {
            context.startActivity(intent)
            result.success("Success")
          } catch (exception: ActivityNotFoundException) {
            result.success("Fail Intent")
          }
        } else {
          result.success("Fail")
        }

      }
      else -> result.notImplemented()
    }
  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }
}
